package com.lujianfei.ann.ui.subui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JLabel;

import com.lujianfei.ann.base.BaseChildWindow;
import com.lujianfei.ann.bean.DataPoint;
import com.lujianfei.ann.utils.MathTool;
import com.lujianfei.ann.widget.ChartDrawPanel;
import com.lujianfei.lib.sdautolayout.impl.SDAutoLayout;
import com.lujianfei.lib.widgets.JLabelEdit;

public class GaussDistributionFrame extends BaseChildWindow {

	ChartDrawPanel drawPanel = new ChartDrawPanel();
	JButton btStartTraining = new JButton("开始生成");
	JLabelEdit mRandomGenTimesEdit = new JLabelEdit("高斯随机生成次数:");
	MathTool mathTool = MathTool.getInstance();
	int randomGenTimes = 80000;
	public static GaussDistributionFrame create() {
		return new GaussDistributionFrame();
	}

	private GaussDistributionFrame() {
		super(800, 800);
		setTitle("正态分布");
		add(drawPanel);
		add(btStartTraining);
		add(mRandomGenTimesEdit);
		mRandomGenTimesEdit.setText(""+randomGenTimes);
		positionView();
		drawPanel.setMinX(0);
		drawPanel.setMaxX(600);
		drawPanel.setMinY(0);
		drawPanel.setMaxY(600);
		reset();
		drawPanel.repaint();

		btStartTraining.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				randomGenTimes = Integer.parseInt(mRandomGenTimesEdit.getText());
				reset();
				drawPanel.repaint();
			}
		});
	}


	private void reset() {
		drawPanel.setPoints(getPoint());
	}
	

	@Override
	protected void onResize() {
		// TODO Auto-generated method stub
		super.onResize();
		positionView();
	}

	private void positionView() {
		SDAutoLayout.forComponent(mRandomGenTimesEdit).widthIs(300).heightIs(35).topSpaceToComponent(this, 5)
		.leftSpaceToComponent(this, 5);
		SDAutoLayout.forComponent(btStartTraining).widthIs(100).heightIs(35).topSpaceToComponent(this, 5)
				.leftSpaceToComponent(mRandomGenTimesEdit, 5);
		
		SDAutoLayout.forComponent(drawPanel).widthIs(getWidth() - 50).heightIs(getHeight() - 100)
				.topSpaceToComponent(btStartTraining, 5);
	}


	private DataPoint[] getPoint() {
		Color color = new Color(0x00ffff);
		List<DataPoint> dataPoint = new ArrayList<DataPoint>();
		// 提供顶部数据集
		Map<Integer,Integer> map = new HashMap<>();
		for (int i = 0; i < randomGenTimes; i++) {
			int random = (int) (mathTool.getGaussian() * 100) + 300;
			if(map.containsKey(random)) {
				map.put(random, map.get(random) + 1);
			} else {
				map.put(random, 0);
			}
		}
		for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
			dataPoint.add(new DataPoint(entry.getKey(), entry.getValue(), color));
		}
		return dataPoint.toArray(new DataPoint[dataPoint.size()]);
	}

}
